package cn.lifei.auth.service.impl;

import cn.lifei.auth.dto.LoginDTO;
import cn.lifei.auth.service.ILoginService;
import cn.lifei.auth.vo.LoginVO;
import cn.lifei.basic.data.ContextMap;
import cn.lifei.org.domain.Employee;
import cn.lifei.org.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;
@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private EmployeeMapper employeeMapper;


    @Override
    public LoginVO login(LoginDTO loginDTO) {
        //校验loginDTO是否为空
        if (Objects.isNull(loginDTO.getUsername()) || Objects.isNull(loginDTO.getPassword()))
        throw new RuntimeException("账号密码为空");

        /**
         * 根据账号查对象
         * 在判断对象密码是否匹配
         * 最后返回结果
         */
        Employee employee = employeeMapper.queryByUsername(loginDTO);
        if (Objects.isNull(employee)) throw new RuntimeException("账号或密码错误");
        if (!employee.getPassword().equals(loginDTO.getPassword().trim()))throw new RuntimeException("账号或密码错误");
        LoginVO loginVO = new LoginVO();
        /**
         * 数据脱敏
         * 给前端指定的数据，如果将id和密码传给前端是很危险的行为，下面就只给了name和age两个属性，
         */
        Employee user = new Employee();
        user.setAge(employee.getAge());
        user.setUsername(employee.getUsername());
        loginVO.setUser(user);
        String token = UUID.randomUUID().toString();
        loginVO.setToken(token);
        /**
         * 存全局map 如果直接使用 employee 脱敏  那么存在map里面的数据就没有id了
         */
        ContextMap.loginMap.put(token,employee);
        return loginVO;
    }
}
